package com.cxf.windex.base.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;

public class HttpUtil {

  public static String getJSON(String httpUrl, String method, String postData, String userName,
      String password) throws IOException {
    System.out.println("httpUrl:" + httpUrl);
    StringBuilder json = new StringBuilder();
    BufferedReader reader = null;
    try {
      URL url = new URL(httpUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      String headerKey = "Authorization";
      // String headerValue =
      // "Basic " + Base64.encodeBase64String((userName + ":" + password).getBytes());

      String headerValue =
          "Basic " + Base64.encodeBase64String((userName + ":" + password).getBytes());

      connection.setRequestProperty(headerKey, headerValue);
      connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
      connection.setRequestMethod(method);
      connection.setDoOutput(true);
      connection.setDoInput(true);

      if (method.equals("POST")) {
        OutputStream os = connection.getOutputStream();
        os.write(postData.getBytes("UTF-8"));
        os.close();
      }


      connection.connect();
      // System.out.println(connection.getResponseCode());
      // if (connection.getResponseCode() == 200) {
      reader =
          new BufferedReader(new InputStreamReader(connection.getInputStream(),
              StandardCharsets.UTF_8));
      String strRead = null;
      while ((strRead = reader.readLine()) != null)
        json.append(strRead);
      // }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      org.apache.commons.io.IOUtils.closeQuietly(reader);
    }
    return json.toString();
  }

  protected HttpURLConnection initHttp(String url) throws Exception {
    URL localURL = new URL(url);
    URLConnection connection = localURL.openConnection();
    HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    return httpURLConnection;
  }

  protected InputStream doOutputIn(HttpURLConnection conn, String method, byte[] protobufBytes)
      throws Exception {
    conn.setDoOutput(true);
    conn.setRequestMethod(method);

    conn.setRequestProperty("Content-Type", "application/x-protobuf");
    conn.setRequestProperty("Accept", "application/x-protobuf");
    OutputStream wr = conn.getOutputStream();
    wr.write(protobufBytes);
    wr.flush();
    wr.close();
    return conn.getInputStream();
  }



  protected InputStream doUpload(HttpURLConnection conn, String method, byte[] fileBytes,
      Map<String, Object> propertys) throws Exception {
    conn.setDoOutput(true);
    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/x-protobuf;charset=UTF-8");
    conn.setRequestProperty("Accept", "application/x-protobuf");
    if (propertys != null) {
      for (String key : propertys.keySet()) {
        System.out.println(key);
        conn.addRequestProperty(key, String.valueOf(propertys.get(key)));
      }
    }
    OutputStream wr = conn.getOutputStream();
    wr.write(fileBytes);
    wr.flush();
    wr.close();
    return conn.getInputStream();
  }



  public String getParams(String method, Map<String, String> paramValues) {
    String params = "";
    Set<String> key = paramValues.keySet();
    String beginLetter = "";
    if (method.equalsIgnoreCase("get")) {
      beginLetter = "?";
    }

    for (Iterator<String> it = key.iterator(); it.hasNext();) {
      String s = (String) it.next();
      if (paramValues.get(s) == null) {
        continue;
      }
      if (params.equals("")) {
        params += beginLetter + s + "=" + URLEncoder.encode(paramValues.get(s));
      } else {
        params += "&" + s + "=" + URLEncoder.encode(paramValues.get(s));
      }
    }
    return params;
  }
}
